package cn.xm.lingshi.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.xm.lingshi.pojo.PageBean;
import cn.xm.lingshi.pojo.User;
import cn.xm.lingshi.service.YonghuService;
import cn.xm.lingshi.service.impl.YongHuServiceImpl;

public class ChaXunYongHuServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		YonghuService userService = new YongHuServiceImpl();
		int currentPageNo = 1;
		int pageSize = 2;
		String queryName = "";
		int roleId = -1; // 用户角色类型
		int totalPageCount = 0; // 总页数
		request.setCharacterEncoding("UTF-8");
		// 查询参数
		queryName = request.getParameter("queryUserName");
		String type = request.getParameter("queryUserType");

		System.out.println("接收的参数queryUserName：" + queryName);
		System.out.println("接收的参数queryUserType：" + type);

		if (type != null && !"".equals(type)) {
			roleId = Integer.parseInt(type);
		}

		String pageNo = request.getParameter("pageno");
		if (pageNo != null && !"".equals(pageNo)) {
			currentPageNo = Integer.parseInt(pageNo);
		}
		totalPageCount = userService.queryTotalPageCount(pageSize, queryName,
				roleId);
		if (totalPageCount > 0) {
			// 控制获取的页码
			if (currentPageNo == 0) {
				currentPageNo = 1;
			}
			if (currentPageNo >= totalPageCount) {
				currentPageNo = totalPageCount;
			}

			PageBean<User> pageBean = userService.queryUserByPageNo(
					currentPageNo, pageSize, queryName, roleId);
			// 设置对象的当前页码
			pageBean.setCurrPageNo(currentPageNo);

			// 将pageBean放入session的作用域内
			HttpSession session = request.getSession();
			session.setAttribute("bean", pageBean);
			session.setAttribute("queryUserType", roleId);
			session.setAttribute("queryUserName", queryName);

			response.sendRedirect("userlist.jsp");
		} else {
			out.print("<script>alert('未查询到数据');location.href='chaxunyonghu'</script>");
		}

		out.close();
	}

}
